<template>
  <div class="video-player" :class="{ fullscreen: isFullscreen }">
    <!-- 关闭按钮 -->
    <div class="close-btn" @click="closeVideo">
      <el-icon><Close /></el-icon>
    </div>
    
    <div class="video-container" ref="videoContainer">
      <video
        ref="videoRef"
        :src="src"
        :poster="poster"
        @loadedmetadata="handleLoadedMetadata"
        @timeupdate="handleTimeUpdate"
        @ended="handleEnded"
        @play="handlePlay"
        @pause="handlePause"
        @click="togglePlay"
      ></video>
      
      <!-- 播放按钮覆盖层 -->
      <div v-if="!isPlaying && !loading" class="play-overlay" @click="play">
        <div class="play-button">
          <el-icon><VideoPlay /></el-icon>
        </div>
      </div>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-overlay">
        <el-icon class="loading-icon"><Loading /></el-icon>
      </div>
      
      <!-- 控制栏 -->
      <div class="video-controls" :class="{ visible: showControls }">
        <!-- 进度条 -->
        <div class="progress-container">
          <div class="progress-bar" @click="handleProgressClick">
            <div class="progress-buffer" :style="{ width: bufferProgress + '%' }"></div>
            <div class="progress-played" :style="{ width: playProgress + '%' }"></div>
            <div class="progress-thumb" :style="{ left: playProgress + '%' }"></div>
          </div>
        </div>
        
        <!-- 控制按钮 -->
        <div class="controls-bar">
          <div class="controls-left">
            <el-button circle size="small" @click="togglePlay">
              <el-icon>
                <VideoPlay v-if="!isPlaying" />
                <VideoPause v-else />
              </el-icon>
            </el-button>
            
            <div class="time-display">
              <span>{{ formatTime(currentTime) }}</span>
              <span>/</span>
              <span>{{ formatTime(duration) }}</span>
            </div>
          </div>
          
          <div class="controls-right">
            <!-- 音量控制 -->
            <div class="volume-control">
              <el-button circle size="small" @click="toggleMute">
                <el-icon>
                  <Mute v-if="isMuted || volume === 0" />
                  <Mic v-else />
                </el-icon>
              </el-button>
              <div class="volume-slider" v-show="showVolumeSlider">
                <el-slider
                  v-model="volume"
                  :min="0"
                  :max="1"
                  :step="0.1"
                  :show-tooltip="false"
                  @input="handleVolumeChange"
                />
              </div>
            </div>
            
            <!-- 播放速度 -->
            <el-dropdown @command="handleSpeedChange">
              <el-button circle size="small">
                <span class="speed-text">{{ playbackRate }}x</span>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="0.5">0.5x</el-dropdown-item>
                  <el-dropdown-item command="0.75">0.75x</el-dropdown-item>
                  <el-dropdown-item command="1">1x</el-dropdown-item>
                  <el-dropdown-item command="1.25">1.25x</el-dropdown-item>
                  <el-dropdown-item command="1.5">1.5x</el-dropdown-item>
                  <el-dropdown-item command="2">2x</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            
            <!-- 全屏按钮 -->
            <el-button circle size="small" @click="toggleFullscreen">
              <el-icon>
                <FullScreen v-if="!isFullscreen" />
                <Aim v-else />
              </el-icon>
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import {
  VideoPlay, VideoPause, Mute, Mic,
  FullScreen, Aim, Loading, Close
} from '@element-plus/icons-vue'

// Props
const props = defineProps({
  src: {
    type: String,
    required: true
  },
  poster: {
    type: String,
    default: ''
  },
  autoplay: {
    type: Boolean,
    default: false
  },
  loop: {
    type: Boolean,
    default: false
  },
  muted: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['play', 'pause', 'ended', 'timeupdate', 'close'])

// 响应式数据
const videoRef = ref()
const videoContainer = ref()
const isPlaying = ref(false)
const loading = ref(false)
const currentTime = ref(0)
const duration = ref(0)
const volume = ref(1)
const isMuted = ref(props.muted)
const playbackRate = ref(1)
const isFullscreen = ref(false)
const showControls = ref(false)
const showVolumeSlider = ref(false)
const bufferProgress = ref(0)
const controlsTimer = ref(null)

// 计算属性
const playProgress = computed(() => {
  return duration.value > 0 ? (currentTime.value / duration.value) * 100 : 0
})

// 方法
const play = () => {
  if (videoRef.value) {
    loading.value = true
    videoRef.value.play()
  }
}

const pause = () => {
  if (videoRef.value) {
    videoRef.value.pause()
  }
}

const togglePlay = () => {
  if (isPlaying.value) {
    pause()
  } else {
    play()
  }
}

const toggleMute = () => {
  if (videoRef.value) {
    videoRef.value.muted = !videoRef.value.muted
    isMuted.value = videoRef.value.muted
  }
}

const toggleFullscreen = () => {
  if (!isFullscreen.value) {
    if (videoContainer.value.requestFullscreen) {
      videoContainer.value.requestFullscreen()
    }
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen()
    }
  }
}

const handleSpeedChange = (speed) => {
  playbackRate.value = parseFloat(speed)
  if (videoRef.value) {
    videoRef.value.playbackRate = playbackRate.value
  }
}

const handleVolumeChange = (newVolume) => {
  if (videoRef.value) {
    videoRef.value.volume = newVolume
    isMuted.value = newVolume === 0
  }
}

const handleProgressClick = (event) => {
  const rect = event.currentTarget.getBoundingClientRect()
  const clickX = event.clientX - rect.left
  const percentage = clickX / rect.width
  const newTime = percentage * duration.value
  
  if (videoRef.value) {
    videoRef.value.currentTime = newTime
  }
}

const formatTime = (time) => {
  const minutes = Math.floor(time / 60)
  const seconds = Math.floor(time % 60)
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

// 事件处理
const handleLoadedMetadata = () => {
  duration.value = videoRef.value.duration
  loading.value = false
}

const handleTimeUpdate = () => {
  currentTime.value = videoRef.value.currentTime
  
  // 更新缓冲进度
  if (videoRef.value.buffered.length > 0) {
    const bufferedEnd = videoRef.value.buffered.end(videoRef.value.buffered.length - 1)
    bufferProgress.value = (bufferedEnd / duration.value) * 100
  }
  
  emit('timeupdate', currentTime.value)
}

const handlePlay = () => {
  isPlaying.value = true
  loading.value = false
  emit('play')
}

const handlePause = () => {
  isPlaying.value = false
  emit('pause')
}

const handleEnded = () => {
  isPlaying.value = false
  emit('ended')
}

const handleFullscreenChange = () => {
  isFullscreen.value = !!document.fullscreenElement
}

const showControlsTemporarily = () => {
  showControls.value = true
  clearTimeout(controlsTimer.value)
  controlsTimer.value = setTimeout(() => {
    if (isPlaying.value) {
      showControls.value = false
    }
  }, 3000)
}

const handleMouseMove = () => {
  showControlsTemporarily()
}

const handleMouseLeave = () => {
  if (isPlaying.value) {
    showControls.value = false
  }
}

const closeVideo = () => {
  pause()
  emit('close')
}

// 生命周期
onMounted(() => {
  if (videoRef.value) {
    videoRef.value.volume = volume.value
    videoRef.value.muted = isMuted.value
    videoRef.value.loop = props.loop
    
    if (props.autoplay) {
      play()
    }
  }
  
  document.addEventListener('fullscreenchange', handleFullscreenChange)
  videoContainer.value?.addEventListener('mousemove', handleMouseMove)
  videoContainer.value?.addEventListener('mouseleave', handleMouseLeave)
})

onUnmounted(() => {
  document.removeEventListener('fullscreenchange', handleFullscreenChange)
  videoContainer.value?.removeEventListener('mousemove', handleMouseMove)
  videoContainer.value?.removeEventListener('mouseleave', handleMouseLeave)
  clearTimeout(controlsTimer.value)
})
</script>

<style lang="scss" scoped>
.video-player {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  background: rgba(0, 0, 0, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  
  .video-container {
    position: relative;
    max-width: 80%;
    max-height: 80vh;
    width: 100%;
    background: #000;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
    
    video {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
  }
  
  &.fullscreen {
    .video-container {
      max-width: 100%;
      max-height: 100vh;
    }
  }
}

.play-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.3);
  cursor: pointer;
  
  .play-button {
    width: 80px;
    height: 80px;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
    
    &:hover {
      background: white;
      transform: scale(1.1);
    }
    
    .el-icon {
      font-size: 32px;
      color: var(--el-color-primary);
      margin-left: 4px;
    }
  }
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.5);
  
  .loading-icon {
    font-size: 48px;
    color: white;
    animation: spin 1s linear infinite;
  }
}

.video-controls {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  padding: 20px 16px 16px;
  opacity: 0;
  transition: opacity 0.3s ease;
  
  &.visible {
    opacity: 1;
  }
}

.progress-container {
  margin-bottom: 12px;
}

.progress-bar {
  position: relative;
  height: 4px;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 2px;
  cursor: pointer;
  
  .progress-buffer {
    position: absolute;
    height: 100%;
    background: rgba(255, 255, 255, 0.5);
    border-radius: 2px;
    transition: width 0.3s ease;
  }
  
  .progress-played {
    position: absolute;
    height: 100%;
    background: var(--el-color-primary);
    border-radius: 2px;
    transition: width 0.1s ease;
  }
  
  .progress-thumb {
    position: absolute;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 12px;
    height: 12px;
    background: var(--el-color-primary);
    border-radius: 50%;
    opacity: 0;
    transition: opacity 0.3s ease;
  }
  
  &:hover .progress-thumb {
    opacity: 1;
  }
}

.controls-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.controls-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.controls-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.time-display {
  color: white;
  font-size: 14px;
  font-family: monospace;
  
  span {
    margin: 0 2px;
  }
}

.volume-control {
  position: relative;
  display: flex;
  align-items: center;
  
  &:hover .volume-slider {
    display: block;
  }
  
  .volume-slider {
    position: absolute;
    bottom: 100%;
    left: 50%;
    transform: translateX(-50%);
    width: 100px;
    padding: 8px;
    background: rgba(0, 0, 0, 0.8);
    border-radius: 4px;
    display: none;
  }
}

.speed-text {
  font-size: 12px;
  color: white;
}

.el-button {
  background: rgba(255, 255, 255, 0.1);
  border: none;
  color: white;
  
  &:hover {
    background: rgba(255, 255, 255, 0.2);
  }
}

.close-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: pointer;
  z-index: 10;
  transition: all 0.2s ease;
  
  &:hover {
    background: rgba(255, 255, 255, 0.2);
    transform: scale(1.1);
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@media (max-width: 768px) {
  .play-overlay .play-button {
    width: 60px;
    height: 60px;
    
    .el-icon {
      font-size: 24px;
    }
  }
  
  .video-controls {
    padding: 12px 8px 8px;
  }
  
  .controls-bar {
    gap: 8px;
  }
  
  .controls-left {
    gap: 8px;
  }
  
  .time-display {
    font-size: 12px;
  }
}
</style>
